package com.ruoyi.system.utils;


import com.ruoyi.common.log.annotation.Log;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板工具类
 */
@Slf4j
public class FreemarkerUtil {

    /**
     * 模板方法
     * @param fltFileName 模板名称
     * @param data 数据
     * @return
     */
    public static String process(String fltFileName,Map<String, Object> data){
        String templatePath = Thread.currentThread().getContextClassLoader().getResource("ftl").getPath();
        log.info("templatePath:{}",templatePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = cfg.getTemplate(fltFileName,"UTF-8");
            template.setEncoding("UTF-8");

            StringWriter out = new StringWriter();
            template.process(data, out);
            out.flush();
            out.close();
            return out.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        Map<String, Object> datas = new HashMap<String, Object>();
        datas.put("code", 33333);
        //短信内容
        String process = FreemarkerUtil.process("sms.flt", datas);
        System.out.println(process);
    }
}
